<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar"
                 left-arrow
                 @click-left="$router.back()"
                 title="黑马头条"></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div v-if="statusCode===0"
           class="loading-wrap">
        <van-loading color="#3296fa"
                     vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div v-if="statusCode===1"
           class="article-detail">
        <!-- 文章标题 -->
        <h1 class="article-title">{{articleInfo.title}}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info"
                  center
                  :border="false">
          <van-image class="avatar"
                     slot="icon"
                     round
                     fit="cover"
                     :src="articleInfo.aut_photo" />
          <div slot="title"
               class="user-name">{{articleInfo.aut_name}}</div>
          <div slot="label"
               class="publish-date">{{articleInfo.pubdate | getRelativeTime }}</div>
          <!-- 关注组件 -->
          <!-- $event表示子组件传递过来的数据！ -->
          <!-- 运用场景： 父组件需要传递某个数据变量给子组件，子组件最终也要改变父组件个数据变量 -->
          <!-- 父组件需要传递  articleInfo.is_followed 给子组件    自定义属性  属性名叫做value-->
          <!-- 子组件需要改变  父组件的 articleInfo.is_followed的数据  自定义事件  自定义事件名叫做  input -->
          <!-- 一个组件只能有一个 v-model指令 -->
          <!-- <follow-user :author-id="articleInfo.aut_id"
                       :value="articleInfo.is_followed"
                       @input="articleInfo.is_followed=$event" /> -->
          <follow-user :author-id="articleInfo.aut_id"
                       v-model="articleInfo.is_followed" />
          <!--
            <input type="text" v-model="变量">
            <input type="text" :value="变量" @input="变量=$event.target.value">
           -->
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div class="article-content markdown-body"
             ref="content"
             v-html="articleInfo.content"></div>
        <van-divider>正文结束</van-divider>

        <!---------------------------------- 文章评论列表-------------------------------- -->
        <comment-list @updateCommentTotal="totalCommentNum=$event"
                      :list="commentListData"
                      @openReply="openReplyPopup"
                      :source-id="articleInfo.art_id" />
        <!---------------------------- /文章评论列表-------------------- -->

        <!---------------------------- 文章评论 ---------------------------->
        <van-popup v-model="isCommentShow"
                   position="bottom">
          <!-- 评论组件 -->
          <comment-post @close="isCommentShow=false"
                        @updateTotal="totalCommentNum++"
                        :list="commentListData"
                        v-if="isCommentShow"
                        :target="articleInfo.art_id" />
        </van-popup>
        <!---------------------------- /文章评论 ---------------------------->

        <!---------------------------- 评论回复 ---------------------------->
        <van-popup v-model="isCommentReply"
                   style="height:100vh"
                   position="bottom">
          <comment-reply v-if="isCommentReply"
                         @click-close="isCommentReply=false"
                         :comment="currentCommentInfo" />
        </van-popup>
        <!---------------------------- /评论回复 ---------------------------->

        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button class="comment-btn"
                      type="default"
                      @click="isCommentShow=true"
                      round
                      size="small">写评论</van-button>
          <van-icon name="comment-o"
                    :badge="totalCommentNum"
                    color="#777" />
          <!-- 使用收藏组件 -->
          <!--
            <collect-article
                :value="articleInfo.is_collecte"
                @input="articleInfo.is_collected=$event"
            />
          -->
          <collect-article :article-id="articleInfo.art_id"
                           v-model="articleInfo.is_collected" />
          <!-- 使用点赞组件 -->
          <!-- <like-article :article-id="articleInfo.art_id"
                        :is-attitude="articleInfo.attitude"
                        @update:isAttitude="articleInfo.attitude=$event"
                           /> -->
          <!-- v-model组件上只能使用一次,sync修饰符可以实现多个双向绑定！ -->
          <!-- 父==>子    <标签 :自定义属性名="变量" /> -->
          <!-- 子==>父    <标签 @update:自定义属性名="变量=$event" /> -->

          <!-- 自定义属性名叫做：props定义：  isAttitude -->
          <!-- 自定义事件名叫做：触发：  this.$emit('update:isAttitude',实参) -->

          <!-- 简写为： <标签 :自定义属性名.sync="变量" /> -->

          <like-article :article-id="articleInfo.art_id"
                        :is-attitude.sync="articleInfo.attitude" />

          <van-icon name="share"
                    color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div v-if="statusCode===2"
           class="error-wrap">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div v-if="statusCode===3"
           class="error-wrap">
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn"
                    @click="loadArticleInfo">点击重试</van-button>
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

  </div>
</template>

<script>
import { getArticleById } from '@/api/article'
import '@/style/github-markdown.css'
import { ImagePreview } from 'vant'
import FollowUser from '@/components/follow-user'
import CollectArticle from '@/components/collect-article'
import LikeArticle from '@/components/like-article'
import CommentList from './components/comment-list'
import CommentPost from './components/comment-post'
import CommentReply from './components/comment-reply'
export default {
  name: 'ArticleIndex',
  components: {
    FollowUser,
    CollectArticle,
    LikeArticle,
    CommentList,
    CommentPost,
    CommentReply
  },
  data () {
    return {
      statusCode: 0, // 0 加载中，1表示加载成功  2加载失败404  3表示其他
      articleInfo: {}, // 文章信息
      totalCommentNum: '', // 文章评论总数
      isCommentShow: false, // 文章评论弹框显示
      commentListData: [], // 文章评论列表数据
      isCommentReply: false, // 评论回复弹框是否显示
      currentCommentInfo: {} // 当前点击的评论项
    }
  },
  created () {
    this.loadArticleInfo()
  },
  // 提供数据
  // provide: { // 对象写法
  //   articleId: 234  // 不能用this，仅限于写死数据
  // },
  provide () { // 函数写法
    return {
      articleId: this.$route.params.id
    }
  },
  methods: {
    // 获取文章详情
    async loadArticleInfo () {
      this.statusCode = 0 // 开始就加载中
      try {
        const { data: res } = await getArticleById(this.$route.params.id)
        this.articleInfo = res.data // 赋值操作
        this.statusCode = 1 // 改变状态码
        // 等到渲染完成,因为状态码变成了1，所以渲染内容需要耗时
        this.$nextTick(() => {
          // 1.获取到所有的img 节点
          // this.$refs.content 文章正文节点
          let imgs = this.$refs.content.querySelectorAll('img')
          // 2.获取所有的图片src内容
          imgs = Array.from(imgs) // 变成数组
          const picArr = imgs.map(val => val.src)
          // 3.图片绑定点击事件
          imgs.forEach((dom, idx) => {
            dom.onclick = function () {
              // 4.调用预览插件
              ImagePreview({
                images: picArr, // 图片数组
                startPosition: idx // 预览开始的位置
              })
            }
          })
        })
      } catch (error) {
        if (error.response.status === 404) {
          this.statusCode = 2
        } else {
          this.statusCode = 3
        }
        console.dir(error)
      }
    },
    // 孙子组件通知打开弹框
    openReplyPopup (val) {
      // 打开弹框
      this.isCommentReply = true
      this.currentCommentInfo = val
    }
  }
}

</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    z-index: 1;
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
